"""

自定义功能
"""
import json
import chardet
import pandas as pd
from io import StringIO
from django.core.files.storage import default_storage
from django.http import JsonResponse, HttpResponse, HttpResponseBadRequest
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import io
from io import StringIO
import os
from django.shortcuts import render, redirect
# from workDjango.utils.BootStrapModelForm import TextFileUploadForm



# 文件上传并保存
# def upload_text_file(request):
#     if request.method == 'POST':  # 如果请求方法是POST，则处理文件上传
#         form = TextFileUploadForm(request.POST, request.FILES)  # 创建表单实例并绑定数据
#         if form.is_valid():  # 验证表单数据是否有效
#             uploaded_file = form.save()  # 将文件保存到数据库和指定的文件系统位置
#             # 读取并处理文本文件内容
#             file_name = uploaded_file.file.name.replace('uploads/', '')
#             print(file_name)
#             file_extension = os.path.splitext(file_name)[1]
#             print(file_extension)
#             # try:
#             if file_extension == '.csv':
#                 # 读取csv文件并转换为DataFrame
#                 df = pd.read_csv(uploaded_file.file)
#                 with uploaded_file.file.open('rb') as f:
#                     df = pd.read_csv(f, header=None)
#             elif file_extension in ['.xls', '.xlsx']:
#                 with uploaded_file.file.open('rb') as f:
#                     df = pd.read_excel(f, header=None)
#             else:
#                 return HttpResponseBadRequest('不支持的文件格式,目前仅支持.csv, .xls, 和 .xlsx 文件')
#             print(df.head())
#             # 这里可以添加对文件内容的进一步处理逻辑
#             return redirect('/system/customize/success')  # 重定向到成功页面
#         # except UnicodeDecodeError:
#         #     return HttpResponseBadRequest('文件编码错误')
#         # except Exception as e:
#         #     print(e)
#         #     return HttpResponseBadRequest('文件读取错误')
#
#     else:
#         form = TextFileUploadForm()  # 如果不是POST请求，创建一个新的空表单实例
#     return render(request, 'customize.html', {'form': form})  # 渲染上传文件的HTML页面
#
#
# def upload_success(request):
#     return render(request, 'customize_success.html')  # 渲染上传成功的提示页面


# 文件上传并保存，并展示数据
# def upload_file(request):
#     if request.method == 'POST' and request.FILES['file']:
#         file = request.FILES['file']
#         # 确保uploads目录存在
#         os.makedirs('media', exist_ok=True)
#         file_path = os.path.join('media', file.name)
#         with open(file_path, 'wb+', ) as destination:
#             for chunk in file.chunks():
#                 destination.write(chunk)
#
#         if file.name.endswith('.csv'):
#             data = pd.read_csv(file_path, header=None)
#         elif file.name.endswith('.xlsx'):
#             data = pd.read_excel(file_path, header=None)
#             # print(data)
#
#         # 将数据转换为JSON格式以便前端使用
#         data_json = data.to_json(orient='records')
#         # print(data_json)
#         # 重定向到展示数据的页面，并将数据作为URL参数传递
#         return redirect(f'/system/customize/show_data?data={data_json}')
#     return render(request, 'upload.html')
#
#
# # 并展示数据
# def show_data(request):
#     data = request.GET.get('data')
#     data = json.loads(data)
#     print(data)
#     return render(request, 'show_data.html', {'data': data})

# [{"0":"aaa","1":123,"2":231,"3":43,"4":165},{"0":"bbb","1":133,"2":133,"3":133,"4":133},{"0":"ccc","1":123,"2":200,"3":78,"4":165},{"0":"ddd","1":143,"2":231,"3":65,"4":154},{"0":"eee","1":123,"2":200,"3":56,"4":165},{"0":"fff","1":193,"2":231,"3":43,"4":133}]
# [{'0': 'aaa', '1': 123, '2': 231, '3': 43, '4': 165}, {'0': 'bbb', '1': 133, '2': 133, '3': 133, '4': 133}, {'0': 'ccc', '1': 123, '2': 200, '3': 78, '4': 165}, {'0': 'ddd', '1': 143, '2': 231, '3': 65, '4': 154}, {'0': 'eee', '1': 123, '2': 200, '3': 56, '4': 165}, {'0': 'fff', '1': 193, '2': 231, '3': 43, '4': 133}]
"""修改版"""


def upload_file(request):
    if request.method == 'POST' and request.FILES['file']:
        file = request.FILES['file']
        # 确保uploads目录存在
        os.makedirs('media', exist_ok=True)
        file_path = os.path.join('media', file.name)
        with open(file_path, 'wb+', ) as destination:
            for chunk in file.chunks():
                destination.write(chunk)

        # if file.name.endswith('.csv'):
        #     data = pd.read_csv(file_path, header=None)
        # elif file.name.endswith('.xlsx'):
        #     data = pd.read_excel(file_path, header=None)
        #     # print(data)
        #
        # # 将数据转换为JSON格式以便前端使用
        # data_json = data.to_json(orient='records')
        # # print(data_json)
        # 重定向到展示数据的页面，并将数据作为URL参数传递
        return redirect(f'/system/customize/show_data?data={file.name}')
    return render(request, 'upload.html')


# 并展示数据
def show_data(request):
    file = request.GET.get('data')
    # print(file)

    file_path = f"media/{file}"
    print(file_path)
    if file.endswith('.csv'):
        try:
            # 使用chardet检擦文件编码
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                print(encoding)
            # 读取文件
            data = pd.read_csv(file_path, header=None, encoding=encoding)
        except UnicodeDecodeError:
            # 如果检测的编码无效，就使用其他编码
            try:
                data = pd.read_csv(file_path, header=None, encoding='latin1')
            except Exception as e:
                print(e)
                return render(request, 'read_file_error.html', {"error": "读取文件失败，暂时不支持当前文件的编码"})
    elif file.endswith('.xlsx'):
        data = pd.read_excel(file_path, header=None)
    elif file.endswith('.txt'):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                print(encoding)
            # 读取文件
            with open(file_path, 'r', encoding=encoding) as f:
                lines = f.read()
            print("txt文件的输出")
            # 将文本转换为DataFrame
            data = pd.read_csv(StringIO(lines), delimiter=',', header=None)
            print(data)
        except UnicodeDecodeError:
            try:
                # 如果检测的编码无效，就是用其他编码
                with open(file_path, 'r', encoding='latin1') as f:
                    lines = f.readline()
                data = pd.read_csv(StringIO(lines), delimiter=',', header=None)
                print(data)
            except Exception as e:
                print(e)
                return render(request, 'read_file_error.html', {"error": "读取文件失败，暂时不支持当前文件的编码"})
    else:
        return render(request, 'read_file_error.html', {"error": "暂时不支持当前文件的格式"})
    # print(data)
    # 将数据转换为JSON格式以便前端使用
    data_json = data.to_json(orient='records')
    data = json.loads(data_json)
    # print(data)
    return render(request, 'show_data.html', {'data': data, "file_name": file})


"""修改版完"""


# 可视化

def visualization(request):
    # if request.method == 'GET':
    file_name = request.GET.get('file')
    x_axis = request.GET.get("x_label")
    y_axis = request.GET.get("y_label")
    visualization_type = request.GET.get("type_label")
    print(file_name, x_axis, y_axis, visualization_type)
    return render(request, 'visualization_work.html',
                  {'file_name': file_name, 'x_axis': x_axis, 'y_axis': y_axis,
                   'visualization_type': visualization_type})


# return render(request, 'visualization.html')


def visualization_show(request):
    file = request.GET.get('file')
    x_axis = str(request.GET.get("x_axis"))
    y_axis = str(request.GET.get("y_axis"))
    visualization_type = request.GET.get("type_axis")
    print(file, x_axis, y_axis, visualization_type)

    file_path = f"media/{file}"
    print(file_path)
    if file.endswith('.csv'):
        try:
            # 使用chardet检擦文件编码
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
            # 读取文件
            data = pd.read_csv(file_path, header=None, encoding=encoding)
        except UnicodeDecodeError:
            try:
                # 如果检测的编码无效，就使用其他编码
                data = pd.read_csv(file_path, header=None, encoding='latin1')
            except Exception as e:
                print(e)
                return render(request, 'read_file_error.html', {"error": "读取文件失败，暂时不支持当前文件的编码"})
    elif file.endswith('.xlsx'):
        data = pd.read_excel(file_path, header=None)
    elif file.endswith('.txt'):
        try:
            with open(file_path, 'rb') as f:
                raw_data = f.read()
                result = chardet.detect(raw_data)
                encoding = result['encoding']
                print(encoding)
            # 读取文件
            with open(file_path, 'r', encoding=encoding) as f:
                lines = f.read()
            # 将文本转换为DataFrame
            data = pd.read_csv(StringIO(lines), delimiter=',', header=None)
            print(data)
        except UnicodeDecodeError:
            # 如果检测的编码无效，就是用其他编码
            with open(file_path, 'r', encoding='latin1') as f:
                lines = f.read()
            data = pd.read_csv(StringIO(lines), delimiter=',', header=None)
            print(data)
        except Exception as e:
            print(e)
            return render(request, 'read_file_error.html', {"error": "读取文件失败，暂时不支持当前文件的编码"})
    else:
        return render(request, 'read_file_error.html', {"error": "暂时不支持当前文件的格式"})
    print(data)

    x_data = data[int(x_axis)].to_list()
    y_data = data[int(y_axis)].to_list()
    print(x_data, y_data)
    x_list = x_data
    y_list = [
        {'name': '数据',
         'type': visualization_type,  # 设置图像类别
         'data': y_data}
    ]
    result = {
        "status": True,
        "data": {
            "x_list": x_list,
            "y_list": y_list
        }
    }
    print(result)
    return JsonResponse(result)
    # print(type(x_data))
    # 将数据转换为JSON格式以便前端使用
    # data_json = data.to_json(orient='records')
    # data = json.loads(data_json)

# def visualize_data(request):
#     if request.method == 'POST':
#         x_axis = request.POST.get('x_axis')
#         y_axis = request.POST.get('y_axis')
#         chart_type = request.POST.get('chart_type')
#         data = request.POST.get('data')
#
#         # 检查data是否为空
#         if not data:
#             return JsonResponse({'error': 'Data parameter is missing or empty'}, status=400)
#
#         try:
#             # 将单引号替换为双引号并解析JSON
#             data = json.loads(data.replace("'", '"'))
#         except json.JSONDecodeError as e:
#             return JsonResponse({'error': 'Invalid JSON format'}, status=400)
#
#         # 这里可以根据chart_type生成不同的ECharts配置
#         option = {
#             'xAxis': {'type': 'category', 'data': [d[x_axis] for d in data]},
#             'yAxis': {'type': 'value'},
#             'series': [{'data': [d[y_axis] for d in data], 'type': chart_type}]
#         }
#         print(f'数据是：{option}')
#         return JsonResponse({'option': option})
#
#     else:
#         data = request.GET.get('data')
#
#         # 检查data是否为空
#         if not data:
#             return JsonResponse({'error': 'Data parameter is missing or empty'}, status=400)
#
#         try:
#             # 将单引号替换为双引号并解析JSON
#             data = json.loads(data.replace("'", '"'))
#         except json.JSONDecodeError as e:
#             return JsonResponse({'error': 'Invalid JSON format'}, status=400)
#
#         return render(request, 'visualize.html', {'data': data})

# 上传文件可视化
